package cn.edu.abtu.service.impl;

import cn.edu.abtu.entity.SysRole;
import cn.edu.abtu.mapper.SysUserMapper;
import cn.edu.abtu.service.SysRoleService;
import cn.edu.abtu.mapper.SysRoleMapper;
import cn.edu.abtu.utils.AjaxResult;
import cn.edu.abtu.vo.query.RoleQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * (SysRole)表服务实现类
 *
 * @author makejava
 * @since 2022-11-16 11:48:23
 */
@Slf4j
@Service
@Transactional
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public AjaxResult page(RoleQueryVo roleQueryVo) {
        Page<SysRole> pageInfo = new Page<>(roleQueryVo.getPageNum(), roleQueryVo.getPageSize());
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(Objects.nonNull(roleQueryVo.getRoleName()), "role_name", roleQueryVo.getRoleName());
        queryWrapper.orderByAsc("id");
        sysRoleMapper.selectPage(pageInfo, queryWrapper);
        return AjaxResult.success("查询成功!", pageInfo);
    }

    @Override
    public AjaxResult removeById(Long id) {
        // 先判断该角色是否有用户使用
        int count = sysRoleMapper.getRoleCountByRoleId(id);
        if (count > 0) {
            return AjaxResult.error("该角色已分配用户,无法删除!");
        }
        // 删除角色权限(角色权限表)
        int result = sysRoleMapper.deleteRolePermissionByRoleId(id);
        if (result > 0) {
            return AjaxResult.error("删除角色失败");
        }
        int i = sysRoleMapper.deleteById(id);
        if (i > 0) {
            return AjaxResult.success("删除角色信息成功!");
        }
        return AjaxResult.error("删除角色失败");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean saveRolePermission(Long roleId, List<Long> permissionIds) {
        // 保存之前先删除已分配的角色信息
        int remove = sysRoleMapper.deleteRolePermissionByRoleId(roleId);
        if (permissionIds.size() == 0){
            return true;
        }else {
            //保存角色菜单信息
            boolean result = sysRoleMapper.saveRolePermission(roleId, permissionIds);
            if (result){
                return true;
            }
        }
        return false;
    }
}
